const Koa = require("koa");
const session = require("koa-session2");
const consola = require("consola");
const { Nuxt, Builder } = require("nuxt");
const bodyParser = require("koa-bodyparser");
const router = require("./routers");

const app = new Koa();

app.use(bodyParser());
// 配置session
app.keys = ["some session"];

const sessionCfg = {
  key: "SESSION1" /** (string) cookie key (default is koa:sess) */,
  maxAge: 86400000,
  overwrite: true /** (boolean) can overwrite or not (default true) */,

  cookie: { maxAge: 2 * 24 * 60 * 60 * 1000 },
  httpOnly: true /** (boolean) httpOnly or not (default true) */,
  signed: true /** (boolean) signed or not (default true) */,
  rolling: false /** (boolean) Force a session identifier cookie to be set on every response. The expiration is reset to the original maxAge, resetting the expiration countdown. default is false **/
};
app.use(session(sessionCfg, app));

app.use(router.routes()).use(router.allowedMethods());

// Import and Set Nuxt.js options
const config = require("../nuxt.config.js");
config.dev = app.env !== "production";

async function start() {
  // Instantiate nuxt.js
  const nuxt = new Nuxt(config);

  const {
    host = process.env.HOST || "127.0.0.1",
    port = process.env.PORT || 3000
  } = nuxt.options.server;

  await nuxt.ready();
  // Build in development
  if (config.dev) {
    const builder = new Builder(nuxt);
    await builder.build();
  }

  app.use(ctx => {
    ctx.status = 200;
    ctx.respond = false; // Bypass Koa's built-in response handling
    ctx.req.session = ctx.session; // session
    ctx.req.ctx = ctx; // This might be useful later on, e.g. in nuxtServerInit or with nuxt-stash
    nuxt.render(ctx.req, ctx.res);
  });

  app.listen(port, host);
  consola.ready({
    message: `Server listening on http://${host}:${port}`,
    badge: true
  });
}

start();
